package com.imooc.config;

import com.imooc.web.filter.LogFilter;
import com.imooc.web.intercepter.TimeInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:   yangdc
 * Date:     2018/9/3 2:07
 */
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private TimeInterceptor timeInterceptor;

    // 配置异步相关参数
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        super.configureAsyncSupport(configurer);
        // 用拦截器拦截异步处理的请求，有如下两个方法注册拦截器，分别对应异步处理的两种方式
        // 区别是有超时时间
        // configurer.registerCallableInterceptors()
        // configurer.registerDeferredResultInterceptors()

        // Runnable使用的简单的异步线程池来处理，线程不可重用
    }

    // 添加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        // registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/login");
        registry.addInterceptor(timeInterceptor).addPathPatterns("/user/*");
    }

    // 将第三方过滤器加入过滤器链
    @Bean
    public FilterRegistrationBean logFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();

        registrationBean.setFilter(new LogFilter());
        // 配置对哪些url起作用
        List<String> urls = new ArrayList<>();
        urls.add("/user/*");
        registrationBean.setUrlPatterns(urls);

        return registrationBean;
    }
}
